package org.stvd.core.jdbc.sequence;

import java.util.HashMap;
import java.util.Map;

import org.stvd.core.util.StringUtil;

public final class SequenceUtil {
    private static final SequenceUtil _instance = new SequenceUtil();
    private final Map<String, KeyInfo> keyMap = new HashMap<String, KeyInfo>(20); // Sequence载体容器
    private static final int POOL_SIZE = 10; // Sequence值缓存大小

    /**
     * 禁止外部实例化
     */
    private SequenceUtil() {
    }

    /**
     * 获取SequenceUtils的单例对象
     * 
     * @return SequenceUtils的单例对象
     */
    public static SequenceUtil getInstance() {
        return _instance;
    }

    /**
     * 获取下一个Sequence键值,下一个Sequence键值，默认缓存的大小为10 
     */
    public synchronized long getNextKeyValue(String keyName) {
        KeyInfo keyInfo = null;
        Long keyObject = null;
        if (keyMap.containsKey(keyName)) {
            keyInfo = keyMap.get(keyName);
        } else {
            keyInfo = new KeyInfo(keyName, POOL_SIZE);
            keyMap.put(keyName, keyInfo);
        }
        keyObject = keyInfo.getKeyValue();
        return keyObject;
    }

    /**
     * 获取下一个Sequence键值,下一个Sequence键值，缓存的大小为proolSize 
     */
    public synchronized long getNextKeyValue(String keyName, int proolSize) {
        KeyInfo keyInfo = null;
        Long keyObject = null;
        if (keyMap.containsKey(keyName)) {
            keyInfo = keyMap.get(keyName);
        } else {
            keyInfo = new KeyInfo(keyName, proolSize);
            keyMap.put(keyName, keyInfo);
        }
        keyObject = keyInfo.getKeyValue();
        return keyObject;
    }

    /**
     * 获取ID串， 例如： idPrefix + '00000123'
     * @param keyName key名称
     * @param idPrefix ID的前缀字符串
     * @param numLen  顺序号生成的字符串的长度
     * @return
     */
    public synchronized String getId(String keyName, String idPrefix, int numLen) {
        KeyInfo keyInfo = null;
        Long keyObject = null;
        if (keyMap.containsKey(keyName)) {
            keyInfo = keyMap.get(keyName);
        } else {
            keyInfo = new KeyInfo(keyName, POOL_SIZE);
            keyMap.put(keyName, keyInfo);
        }
        keyObject = keyInfo.getKeyValue();
        return idPrefix + StringUtil.frontCompWithZore(keyObject, numLen);
    }

}
